package com.mobilebsc.httpclient.callback;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.loopj.android.http.JsonHttpResponseHandler;
import com.mobilebsc.datatype.Perspective;

public class PerspectiveHttpResponseHandler extends JsonHttpResponseHandler {

	private static final String TAG = "PerspectiveHttpResponseHandler";
	private IAsyncTaskCompleteListener<List<Perspective>> callback;
	private List<Perspective> perspectivesList;

	public PerspectiveHttpResponseHandler(
			IAsyncTaskCompleteListener<List<Perspective>> callback) {
		super();
		this.callback = callback;
		perspectivesList = null;
	}

	@Override
	public void onStart() {
		Log.i(TAG, "onStart = loading data");
	}

	@Override
	public void onSuccess(JSONArray perspectives) {

		Log.i(TAG, "onSuccess = JSON length " + perspectives.length()
				+ ", JSON string " + perspectives.toString());

		perspectivesList = new ArrayList<Perspective>();
		JSONObject perspectiveJSON = new JSONObject();

		if (perspectives.length() == 0) {
			perspectivesList.add(new Perspective());
		} else {
			for (int i = 0; i < perspectives.length(); i++) {
				try {
					perspectiveJSON = perspectives.getJSONObject(i);
					Perspective perspective = new Perspective(perspectiveJSON);
					perspectivesList.add(perspective);
				} catch (JSONException e) {
					Log.e(TAG, "onSuccess = " + e.toString());
				}
			}
		}
	}

	@Override
	public void onSuccess(JSONObject singlePerspective) {
		perspectivesList = new ArrayList<Perspective>();

		if (singlePerspective == null) {
			perspectivesList.add(new Perspective());
		} else {
			try {
				Perspective perspective = new Perspective(singlePerspective);
				perspectivesList.add(perspective);
			} catch (JSONException e) {
				Log.e(TAG, "onSuccess = " + e.toString());
			}
		}
	}

	@Override
	public void onFinish() {
		Log.i(TAG, "onFinish = finished");
		callback.onTaskComplete(perspectivesList);
	}

	@Override
	public void onFailure(Throwable e, String response) {
		Log.e(TAG, "onFailure = " + e.toString() + "\n\n" + response);
	}
}